package com.bawei.rk_01.fm

import android.annotation.SuppressLint
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.utils.mvvm.BaseFragment
import com.bawei.base.utils.param.OrderDetail
import com.bawei.base.utils.param.Poeder
import com.bawei.rk_01.Adapter.CarAdapter
import com.bawei.rk_01.R
import com.bawei.rk_01.car.CarViewModel
import com.bawei.rk_01.databinding.FragmentCarBinding
import com.blankj.utilcode.util.ToastUtils
import kotlin.math.truncate

class CarFragment : BaseFragment<FragmentCarBinding,CarViewModel>() {

    lateinit var carAdapter: CarAdapter

    var falg = true // 是否是单个删除
    var carSum = 0

    override fun getViewModel(): Class<CarViewModel> {
        return CarViewModel::class.java
    }

    override fun getLayout(): Int {
        return R.layout.fragment_car
    }

    override fun initView() {

        carAdapter = CarAdapter()
        viewModel.car("true",5,1)
        binding.rvCar.layoutManager = LinearLayoutManager(requireContext())
        binding.rvCar.adapter = carAdapter

        //点击管理切换
        var f = true
        binding.manage.setOnClickListener {
            f = !f
            if (f){
                binding.llManger1.isVisible = false
                binding.llManger2.isVisible = true
            }else{
                binding.llManger1.isVisible = true
                binding.llManger2.isVisible = false
            }
        }

        //子布局点击事件
        carAdapter.addChildClickViewIds(R.id.red,R.id.add,R.id.dx)
        carAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.dx->{

                    //更新选择状态   data修改为对应的状态    后台不需要操作
                    carAdapter.data.get(position).isCheck = !carAdapter.data.get(position).isCheck

                }
                R.id.red->{

                    //数量减
                    carAdapter.data.get(position).cartNum--
                    val add = carAdapter.getViewByPosition(position, R.id.sum) as TextView
                    add.text = "${carAdapter.data.get(position).cartNum}"
                    //当数量变成1后，减不可用
                    if (carAdapter.data.get(position).cartNum == 1){
                        val red = carAdapter.getViewByPosition(position, R.id.red) as TextView
                        red.isEnabled = false
                    }
                    //调用接口
                    viewModel.updatecar(carAdapter.data.get(position).id,carAdapter.data.get(position).cartNum)

                }
                R.id.add->{

                    //点击加号当前购物车数量增加      data修改为对应的状态    后台重新调用接口
                    carAdapter.data.get(position).cartNum++
                    val add = carAdapter.getViewByPosition(position, R.id.sum) as TextView
                    add.text = "${carAdapter.data.get(position).cartNum}"
                    //点击加时，一直可以加
                    val red = carAdapter.getViewByPosition(position, R.id.red) as TextView
                    red.isEnabled = true
                    //调用接口
                    viewModel.updatecar(carAdapter.data.get(position).id,carAdapter.data.get(position).cartNum)

                }
            }
            //子布局点击事件，会影响下方全选和金额的变化
            checkBottom()
        }

        //点击全选，子布局控件也全部选中
        binding.cb.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked){
                carAdapter.data.forEach {
                    it.isCheck = true
                }
            }else{
                carAdapter.data.forEach {
                    it.isCheck = false
                }
            }
            carAdapter.notifyDataSetChanged()
            checkBottom()
        }

        //滑动删除单个购物车数据
        ItemTouchHelper(object : ItemTouchHelper.Callback() {
            override fun getMovementFlags(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder
            ): Int {
                //左滑操作
                val left = ItemTouchHelper.LEFT
                return makeMovementFlags(0,left)
            }

            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return true
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                //滑动结束执行的操作
                val position = viewHolder.layoutPosition // 获取下标
                //先删后台
                viewModel.delcar(arrayOf(carAdapter.data.get(position).id))
                //再删页面数据
                carAdapter.data.removeAt(position)
                //局部刷新
                carAdapter.notifyItemRemoved(position)
                //底部金额发送变化
                checkBottom()
            }
        }).attachToRecyclerView(binding.rvCar)

        //点击批量删除
        binding.del.setOnClickListener {
            //判断是否选中
            val list = arrayListOf<Boolean>()
            carAdapter.data.forEach {
                list.add(it.isCheck)
            }
            if (true in list){
                //有选中的
                var ids = arrayOf<Int>()
                carAdapter.data.forEach {
                    if (it.isCheck){
                        ids += it.id
                    }
                }
                //调用接口
                viewModel.delcar(ids)
                falg = false // 现在是批量删除
            }else{
                ToastUtils.showLong("请选中一个商品")
            }
        }

        //点击立即下单 跳转预下单列表详情
        binding.order.setOnClickListener {
            //判断是否选中商品
            val list = arrayListOf<Boolean>()
            carAdapter.data.forEach {
                list.add(it.isCheck)
            }
            if (true in list){
                //有选中的 , 将其添加到 poeder 中的 orderDetails 中  orderDetails是一个集合，可以有多个下单对象
                val poeder = Poeder()
                poeder.preOrderType = "shoppingCart"
                val orderDetails = ArrayList<OrderDetail>()
                carAdapter.data.forEach {
                    if (it.isCheck){
                        val orderDetail = OrderDetail()
                        orderDetail.shoppingCartId = it.id
                        orderDetails.add(orderDetail)
                    }
                }
                poeder.orderDetails = orderDetails
                viewModel.order(poeder)
            }else{
                ToastUtils.showLong("请选中一个商品")
            }
        }

    }

    @SuppressLint("SetTextI18n")
    private fun checkBottom() {

        //1，全选状态 2.选中数量 3.金额
        //判断是否全选  data中是否有选中的 有 非全选 没有 全选
        var count = 0
        var money = 0f
        val list = mutableListOf<Boolean>()
        carAdapter.data.forEach {
            list.add(it.isCheck)
            if (it.isCheck){
                count++
                money += it.cartNum * it.price.toFloat()
            }
        }

        //详解
        //如果集合中添加的子布局控件选中状态中有非选中状态，全选按钮为非选中状态
        //如果集合中添加的子布局控件选中状态中全部是选中状态，全选按钮为选中状态
        binding.cb.isChecked = false !in list
        //当购物车中没有数据时，全选按钮为不可用
        binding.cb.isEnabled = carAdapter.data.size != 0

        binding.cb.text = "全选（${count}）"
        binding.amount.text = "合计：￥${money}"
        binding.sum.text = "购物车车数量（${list.size}）"
        carSum = list.size

    }

    override fun initData() {

        viewModel.carsuccess.observe(this){
            if (it.code == 200){
                carAdapter.data.clear()
                carAdapter.data.addAll(it.data.list)
                carAdapter.notifyDataSetChanged()
            }else{
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.updatecarsuccess.observe(this){
            if (it.code == 200){
                ToastUtils.showLong("修改成功")
            }
        }
        viewModel.updatecarfail.observe(this){
            ToastUtils.showLong(it)
        }

        //删除
        viewModel.delcarsuccess.observe(this){
            if (it.code == 200){
                ToastUtils.showLong("删除成功")
                if (!falg){
                    viewModel.car("true",5,1)
                    binding.cb.text = "全选（0）"
                    binding.cb.isChecked = false
                    binding.amount.text = "0.00"
                    binding.sum.text = "购物车数量（${carSum}）"
                    falg = true //标志为更新为默认状态
                }
            }else{
                ToastUtils.showLong(it.message)
            }
        }

        //预下单
        viewModel.ordersuccess.observe(this){
            if (it.code == 200){
                //跳转到展示预下单页面
//                ARouter.getInstance().build("").navigation()
                ToastUtils.showLong(it.data.preOrderNo)
            }else{
                ToastUtils.showLong(it.message)
            }
        }

    }

}